package com.anywhere.freightman.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anywhere.freightman.common.entity.car.LocationEntity;
import com.anywhere.freightman.common.entity.car.TrackPoint;
import com.anywhere.freightman.common.ex.CustomException;
import com.google.common.base.Strings;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CarLocationBeidouClient implements ICarLocationClient {
    private final static Logger LOGGER = LoggerFactory.getLogger(CarLocationBeidouClient.class);
    private final static String CAR_BEIDOU_LOCATION_TOKEN = "car_beidou_location_token";

    @Value("${car.location.beidou.username}")
    private String username;
    @Value("${car.location.beidou.pwd}")
    private String pwd;
    @Value("${car.location.beidou.host-name}")
    private String hostName;

    @Autowired
    private BeidouClient beidouClient;

    @Autowired
    private RedisClient redisClient;

    public String getToken() {
        String token = redisClient.getString(CAR_BEIDOU_LOCATION_TOKEN);
//        String token = "";
        if (Strings.isNullOrEmpty(token)) {
            JSONObject jsonObject = JSON.parseObject(beidouClient.getToken(username, pwd));
            token = jsonObject.getString("JSESSIONID");
            redisClient.setValue(CAR_BEIDOU_LOCATION_TOKEN, token);
        }
        return token;
    }

    public String getDeviceId(String carNumber) {
        String token = getToken();
        String str = beidouClient.getDeviceId(token, carNumber);
        JSONObject jsonObject = JSON.parseObject(str);
        int result = jsonObject.getInteger("result");
        if (result != 0) {
            throw new CustomException("接口异常");
        }

        JSONArray devices = jsonObject.getJSONArray("devices");
        if (devices.size() == 1) {
            return devices.getJSONObject(0).getString("did");
        } else {
            for (int i = 0; i < devices.size(); i++) {
                JSONObject device = devices.getJSONObject(i);
                if (device.getIntValue("type") == 0) {
                    return device.getString("did");
                }
            }
        }

        return "";
    }

    @Override
    public LocationEntity getLastLocation(String carNumber) {
        String token = getToken();
        String str = beidouClient.getLastLocation(token, carNumber, 2);
        JSONObject jsonObject = JSON.parseObject(str);
        int result = jsonObject.getInteger("result");
        if (result == 0) {
            JSONArray infos = jsonObject.getJSONArray("infos");
            JSONObject locationJson = infos.getJSONObject(0);
            LocationEntity entity = new LocationEntity();
            entity.setVno(carNumber);
            entity.setAdr(locationJson.getString("pos"));
            long jd = locationJson.getLongValue("jd");
            long wd = locationJson.getLongValue("wd");
            entity.setLat(jd / 1000000.0 * 600000.0);
            entity.setLon(wd / 1000000.0 * 600000.0);
            entity.setUtc(locationJson.getLongValue("tm"));
            return entity;
        } else {
            throw new CustomException("定位失败");
        }
    }

    @Override
    public List<TrackPoint> getTrack(String carNumber, long startTime, long endTime) {
        String token = getToken();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String st = sdf.format(new Date(startTime));
        String et = sdf.format(new Date(endTime));
        String deviceId = getDeviceId(carNumber);
        String str = beidouClient.getCarTrackDetail(token, deviceId, st, et, 2);
        JSONObject jsonObject = JSON.parseObject(str);
        List<TrackPoint> list = new ArrayList<>();
        int result = jsonObject.getInteger("result");
        if (result == 0) {
            JSONArray tracks = jsonObject.getJSONArray("tracks");
            for (int i = 0; i < tracks.size(); i++) {
                JSONObject item = tracks.getJSONObject(i);
                TrackPoint point = new TrackPoint();
                long jd = item.getLongValue("lat");
                long wd = item.getLongValue("lng");
                point.setLat(jd / 1000000.0 * 600000.0);
                point.setLon(wd / 1000000.0 * 600000.0);
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd/HHmmss");
                //2015-12-14 18:54:58.0
                String gt = item.getString("gt");
                try {
                    point.setGtm(sdf2.format(sdf.parse(gt)));
                } catch (ParseException e) {
                    throw new CustomException("系统错误");
                }
                point.setSpd(item.getDouble("sp") / 10.0);
                point.setAgl(item.getIntValue("hx"));
                list.add(point);
            }
        } else {
            throw new CustomException("查询失败");
        }

        return list;
    }

    public static void main(String[] args) throws ParseException {
        String str = "2015-12-14 18:54:58.0";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(str);
        System.out.println(date);
    }
}
